package com.t194.service.impl;

import com.t194.entity.Permission;
import com.t194.entity.Role;
import com.t194.mapper.PermissionMapper;
import com.t194.mapper.RoleMapper;
import com.t194.service.RoleService;
import com.t194.util.NodeState;
import com.t194.util.TreeNode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

@Service("roleService")
@Transactional
public class RoleServiceImpl implements RoleService {
    //依赖注入
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;
    @Override
    public List<Role> searchAll() {
        return roleMapper.findAll();
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void batchDel(Integer[] ids) {
        roleMapper.batchDel(ids);
    }

    @Override
    public int add(Role role) {
        return roleMapper.add(role);
    }

    @Override
    public void update(Role role) {
        roleMapper.update(role);
    }

    @Override
    public List<TreeNode> search4Tree() {
        List<Permission> list = permissionMapper.findByParentId(null);
        return list.stream()
                .map(perm->{
                    TreeNode node01 = transfer(perm);
                    Integer id = node01.getId();
                    List<Permission> list2 = permissionMapper.findByParentId(id);
                    for (Permission p2 : list2) {
                        TreeNode node02 = transfer(p2);
                        node01.getNodes().add(node02);
                        List<Permission> list3 = permissionMapper.findByParentId(p2.getId());
                        list3.forEach(p3->{
                            TreeNode node03 = transfer(p3);
                            node02.getNodes().add(node03);
                        });
                    }
                    return node01;
                })
                .collect(toList());
    }
    private TreeNode transfer(Permission permission) {
        TreeNode treeNode = new TreeNode();
        treeNode.setId(permission.getId());
        treeNode.setText(permission.getName());
        int count = permissionMapper.count(treeNode.getId());
        if (count > 0) {
            treeNode.setNodes(new ArrayList<>());
        }
        NodeState state = new NodeState();
        treeNode.setState(state);
        return treeNode;
    }
}
